<?php
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
$myPdo = DbUtils::createPdoInst();
$page_id = MiscUtils::getParam('i', NULL);
$folder = basename(dirname(__FILE__));
$tag_id = MiscUtils::getParam('tag', TAG_NEWS_ID);
$tag = MiscUtils::getParam('tag', 'product');
$post_id = MiscUtils::getParam('id', 0);
$instance_id = MiscUtils::getParam('inid', 0);

$item = NULL;
$cond_vals = new stdClass(); 
$cond_vals->c = 't.id = :v1';
$cond_vals->v = array(':v1' => $post_id);
$tmp = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'art_post', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
if (count($tmp) > 0) {
  $item = $tmp[0];
}

$tags = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'art_tag', NULL, 't.order', 'ASC', NULL, NULL, NULL)->d;
?>
<style>
* {
  font-family: Trebuchet MS;
  font-size: 12px;
  padding: 0;
  margin: 0;
}
table.form {
  background-color: #fff;
  border-top: 1px solid #222;
  border-left: 1px solid #222;
}
table.form th.header {
  text-align: left;
  color: #fff;
  background-color: #222;
  padding-left: 5px;
  font-weight: bold;
  height: 25px;
  border-bottom: 1px solid #222;
  border-right: 1px solid #222;
}
table.form td {
  vertical-align: middle;
}
table.form td.title {
  background-color: #666;
  border-bottom: 1px solid #222;
  border-right: 1px solid #222;
  width: 150px;
  color: #fff;
  padding: 3px 5px; 
  vertical-align: top;
  font-weight: bold;
}
table.form td.content {
  padding-left: 2px;
  border-bottom: 1px solid #222;
  border-right: 1px solid #222;
  width: 610px;
}
table.form td.content input[type=text],textarea,select,option {
  width: 98%;
  border: 0;
  padding: 0;
  margin: 0;
}
table.form td.content select {
  border: 1px solid #ddd;
}
table.form td.content input[type=text] {
  height: 20px;
}
table.form td.content textarea {
  height: 50px;
  resize: none;
}
table.form3 {
  background-color: #cecece;
  border: 1px solid #222;
  color: #000;
  padding: 2px;
  cursor: pointer;
  display: inline-block;
  margin: 2px;
  font-weight: normal;
}
table.form3 td.text {
  width: 80px;
  height: 20px;
  overflow: hidden;
  display: inline-block;
}
table.form3 td.img {
  width: 16px;
  padding-left: 2px;
}
table.form3:hover td {
  background: #fff;
}
.imgbtn {
  background-image: url(assets/imgs/save.png);
  background-repeat: no-repeat;
  background-position: 5px 2px;
  padding: 5px 5px 5px 30px;
  border: 1px solid #666;
  background-color: #fff;
  cursor: pointer;
  border-radius: 3px;
}
.imgbtn:hover {
  background-color: #eee;
}
</style>
</head>
<body>
<table class="form" cellpadding=0 cellspacing=0>
  <tr><th class="header" colspan=2>Edit Article</th></tr>
  <tr>
    <td class="title">Subject</td>
    <td class="content"><input id="title" class="text" value="<?php echo (isset($item->title) ? $item->title : ''); ?>" type="text" ></input></td>
  </tr>
  <tr>
    <td id="date_title" class="title">Date</td>
    <td id="date_content" class="content"><input type="text" id="date" value="<?php echo (($item) ? "$item->date" : date('Y-m-d', time())); ?>"></input></td>
  </tr>
  <tr>
    <td id="tag_title" class="title">Categories</td>
    <td id="tag_content" class="content"><select id="tag_select" onchange="change_tags(this);"></select></td>
  </tr>
  <tr id="tag_dev">
    <td class="title">&nbsp;</td>
    <td id="tags" class="content">&nbsp;</td>
  </tr>
  <tr>
    <td class="title">Content</td>
    <td class="content"><textarea id="detail" ><?php echo ($item ? $item->content : ''); ?></textarea></td>
  </tr>
</table>
<button class="imgbtn" onclick="save();" style="margin-top: 5px;">Save</button>
<script type="text/javascript" src="../../../libs/json/json2.js"></script>
<script type="text/javascript" src="../../../libs/jquery/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="../../../libs/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript" src="../../../incls/js/myutils.js"></script>
<script type="text/javascript" src="../../../incls/js/pageutils.js"></script>
<script src="../../../libs/jquery_ui/js/jquery-ui-1.10.2.custom.js"></script>
<link href="jquery_ui/css/smoothness/jquery-ui-1.10.2.custom.css" rel="stylesheet">
<script type="text/javascript">
  var _item = JSON.parse('<?php echo addslashes(json_encode($item)); ?>');
  var _tags = JSON.parse('<?php echo addslashes(json_encode($tags)); ?>');
  var _selects = [];
  
  $(function(){
    //NOT GOOD
    parent.document.getElementById('real_last').style.display = 'block';
    
    var div = parent.document.getElementById('<?php echo LAST_NAV; ?>');
    var div_parent = div.parentNode;
    MyUtils.removeChildElements(div_parent);
    var elm;
    elm = parent.document.createElement('a');
    elm.href = '#';
    elm.style.color = '#000';
    elm.style.fontSize = '13px';
    elm.style.fontWeight = 'bold';
    elm.onclick = function() {
      var url = parent.document.URL.replace('&script=index_post', '');
      url = url.replace('&id=<?php echo $post_id; ?>', '');
      url = url.replace('#', '');
      parent.location.href = url;
    };
    elm.appendChild(parent.document.createTextNode('Articles'));
    div_parent.appendChild(elm);

    var td;
    td = div_parent.parentNode.insertCell(-1);
    td.style.width = '20px';
    td.style.textAlign = 'center';
    td.style.color = '#aaa';
    td.appendChild(parent.document.createTextNode('>'));
    
    td = div_parent.parentNode.insertCell(-1);
    td.style.height = '25px';
    td.style.color = '#333';
    td.style.fontSize = '13px';
    if (_item && _item.id) {
      td.appendChild(parent.document.createTextNode(MyUtils.getShort(_item.title, 12)));
    } else {
      td.appendChild(parent.document.createTextNode('New Article'));
    }
    //NOT GOOD END
    
    MyUtils.cleanDatepicker();
    $("#date").datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: "yy-mm-dd",
      yearRange: "2000:" + new Date().getFullYear(),
      showButtonPanel: true,
    });
    
    <?php if ($item) { ?>
    _selects = __decode('<?php echo $item->tag_ids; ?>');
    set_selects();
    <?php } else { ?>
    for (var idx in _tags) {
      var obj = _tags[idx];
      if (obj.id == '<?php echo $tag_id; ?>') {
        _selects[_selects.length] = obj.id;
        set_selects();
        break;
      }
    }
    <?php } ?>
    
    set_tag(PageUtils.getRoot(JSON.parse('<?php echo addslashes(json_encode($tags)); ?>')), $('#tag_select')[0], '');

    tinyMCE.init( {
      // General options
      mode: 'exact',
      elements: 'detail',
      theme: 'advanced',

      plugins: 'pdw,filebrowser,autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist',
      // Theme options
      theme_advanced_buttons1: 'pdw_toggle,|,undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect,|,forecolor,backcolor,|,image,media,|,preview',
      theme_advanced_buttons2: 'search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,cleanup,help,code,|,insertdate,inserttime',
      theme_advanced_buttons3: 'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,advhr,|,print,|,ltr,rtl,|,fullscreen',
      theme_advanced_buttons4: 'insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak',
      theme_advanced_toolbar_location: 'top',
      theme_advanced_toolbar_align: 'left',
      theme_advanced_statusbar_location: 'bottom',
      theme_advanced_resizing: true,

      file_browser_callback: 'filebrowser',
      pdw_toggle_on: '1',
      pdw_toggle_toolbars: '2,3,4',

      height : '480',

      // Example content CSS (should be your site CSS)
      theme_advanced_font_sizes: '10px,11px,12px,13px,14px,15px,16px,17px,18px,19px,20px,21px,22px,23px,24px,25px,26px,27px,28px,29px,30px',
    });
  });

  function change_tags(elm) {
    if (elm) {
      _selects[_selects.length] = elm.options[elm.selectedIndex].value;
    }
    set_selects();
    MyUtils.removeChildElements($('#tag_select')[0]);
    set_tag(PageUtils.getRoot(JSON.parse('<?php echo addslashes(json_encode($tags)); ?>')), $('#tag_select')[0], '');
  }
  
  function set_selects() {
    if (_selects.length == 0) {
      $('#tag_dev')[0].style.display = 'none';
      $('#tag_title')[0].style.borderBottom = '1px solid #222';
      $('#tag_content')[0].style.borderBottom = '1px solid #222';
      return;
    }
    $('#tag_dev')[0].style.display = 'table-row';
    $('#tag_title')[0].style.borderBottom = 'none';
    $('#tag_content')[0].style.borderBottom = 'none';
    MyUtils.removeChildElements($('#tags')[0]);
    for (var idx in _selects) {
      var obj = _selects[idx];
      var func = function(opts) {
        for (var idx in _selects) {
          var obj = _selects[idx];
          if (obj == opts.id) {
            _selects.splice(idx, 1);
          }
        }
        change_tags(null);
      }
      $('#tags')[0].appendChild(__get_imgbtn(__id_to_tag(obj), func, { id: obj }));
    }
    parent.updateHeight_<?php echo $instance_id; ?>();
  }

  function __decode(str) {
    var rslt = str.split('|');
    if (rslt.length < 3) {
      return [];
    }
    rslt.splice(0, 1);
    rslt.splice(rslt.length - 1, 1);
    return rslt;
  }

  function __encode(arr) {
    var rslt = '|';
    for (var idx in arr) {
      var obj = arr[idx];
      rslt += obj + '|';
    }
    return rslt;
  }

  function __id_to_tag(id) {
    for (var idx in _tags) {
      var obj = _tags[idx];
      if (obj.id == id) {
        return obj.name;
      }
    }
    return '';
  }
  
  function __get_imgbtn(name, del_func, opts) {
    var table, tr, td, elm;
    table = document.createElement('table');
    table.className = 'form3';
    table.cellPadding = 0;
    table.cellSpacing = 0;
    tr = table.insertRow(-1);
    td = tr.insertCell(-1);
    td.className = 'text';
    td.title = name;
    td.appendChild(document.createTextNode(name));
    td = tr.insertCell(-1);
    td.className = 'img';
    td.onclick = td.onclick = function() {
      del_func(opts);
    };
    elm = document.createElement('img');
    elm.src = 'assets/imgs/delete24.png';
    td.appendChild(elm);
    return table;
  }

  function save() {
    var obj = {
      <?php if ($item) echo "id: $item->id,"; ?>
      date: $('#date')[0].value,
      title: $('#title')[0].value,
      tag_ids: __encode(_selects),
      content: tinyMCE.get('detail').getContent()
    };
    $.ajax({
      type: "POST",
      url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
      data: "action=save&q=" + encodeURIComponent(JSON.stringify(obj)),
      success: function(msg){
        var obj = JSON.parse(msg);
//        parent.location.href = 'http://<?php echo URL . "admin.php?i=$page_id"; ?>';
        parent.location.href = 'http://<?php echo URL . "admin.php?i=$page_id&script=index_post&tag=$tag_id&id="; ?>' + obj.id;
      }
    });
  }

  function set_tag(node, elm, prefix) {
    node.title = (node.name) ? node.name : node.title;
    if (node.title == 'Root') {
      node.title = '-';
    }
    var opt = new Option(((prefix == '') ? '' : prefix + ') ' ) + ((node.id != 0 && (node.title == '' || !node.title)) ? 'Untitled' : node.title), node.id);
    elm.options[elm.options.length] = opt;
    var exist = 0;
    for (var idx in _selects) {
      var obj = _selects[idx];
      if (obj == node.id) {
        exist = 1;
      }
    }
    if (exist == 1) {
      opt.disabled = 1;
    }
    
    for (var idx in node._children) {
      var obj = node._children[idx];
      set_tag(obj, elm, ((prefix == '') ? '(' : '\u2002' + prefix + '-' ) + (parseInt(idx, 10) + 1));
    }
  }
</script>
